/**
 * 资源管理器
 * 负责游戏资源的计算、更新和管理
 */

import { GAME_CONFIG } from '../config/game-config.js';

export class ResourceManager {
    constructor(gameData) {
        this.gameData = gameData;
    }

    /**
     * 根据时间更新资源
     */
    updateResourcesBasedOnTime() {
        const now = Date.now();
        const lastUpdate = this.gameData.lastUpdate || now;
        const hoursPassed = (now - lastUpdate) / (1000 * 60 * 60);

        if (hoursPassed <= 0) return;

        // 计算木材产出
        const woodProduction = this.calculateProduction('wood', hoursPassed);
        this.gameData.resources.wood += woodProduction;

        // 计算粮食产出
        const foodProduction = this.calculateProduction('food', hoursPassed);
        this.gameData.resources.food += foodProduction;

        // 人口消耗粮食
        const foodConsumption = this.calculateFoodConsumption(hoursPassed);
        this.gameData.resources.food -= foodConsumption;

        // 确保资源不为负数
        this.gameData.resources.wood = Math.max(0, this.gameData.resources.wood);
        this.gameData.resources.food = Math.max(0, this.gameData.resources.food);

        // 如果粮食不足，可能减少人口
        if (this.gameData.resources.food <= 0) {
            this.applyStarvationPenalty();
        }

        this.gameData.lastUpdate = now;
    }

    /**
     * 计算资源产出
     * @param {string} resourceType - 资源类型 ('wood' 或 'food')
     * @param {number} hours - 经过的小时数
     * @returns {number} 产出量
     */
    calculateProduction(resourceType, hours = 1) {
        let production = 0;

        if (resourceType === 'wood') {
            const sawmill = this.gameData.buildings.find(b => b.id === 'sawmill');
            if (sawmill && sawmill.unlocked) {
                production = sawmill.baseProduction * sawmill.level * sawmill.efficiency * hours;
            }
        } else if (resourceType === 'food') {
            const farm = this.gameData.buildings.find(b => b.id === 'farm');
            if (farm && farm.unlocked) {
                production = farm.baseProduction * farm.level * farm.efficiency * hours;
            }
        }

        return Math.floor(production);
    }

    /**
     * 计算每小时资源产出（用于UI显示）
     * @param {string} resourceType - 资源类型
     * @returns {number} 每小时产出
     */
    getProductionPerHour(resourceType) {
        const production = this.calculateProduction(resourceType, 1);

        if (resourceType === 'food') {
            const consumption = this.calculateFoodConsumption(1);
            return production - consumption;
        }

        return production;
    }

    /**
     * 计算粮食消耗
     * @param {number} hours - 经过的小时数
     * @returns {number} 消耗量
     */
    calculateFoodConsumption(hours = 1) {
        const consumption = this.gameData.resources.population *
                          GAME_CONFIG.RESOURCES.FOOD_CONSUMPTION_PER_HOUR *
                          hours;
        return Math.floor(consumption);
    }

    /**
     * 应用饥饿惩罚
     */
    applyStarvationPenalty() {
        const newPopulation = Math.floor(
            this.gameData.resources.population * GAME_CONFIG.RESOURCES.STARVATION_PENALTY
        );
        this.gameData.resources.population = Math.max(1, newPopulation);
        console.log('粮食不足，人口减少至:', this.gameData.resources.population);
    }

    /**
     * 添加资源
     * @param {string} resourceType - 资源类型
     * @param {number} amount - 数量
     */
    addResource(resourceType, amount) {
        if (this.gameData.resources.hasOwnProperty(resourceType)) {
            this.gameData.resources[resourceType] += amount;
            this.gameData.resources[resourceType] = Math.max(0, this.gameData.resources[resourceType]);
        }
    }

    /**
     * 扣除资源
     * @param {string} resourceType - 资源类型
     * @param {number} amount - 数量
     * @returns {boolean} 是否成功扣除
     */
    deductResource(resourceType, amount) {
        if (this.gameData.resources.hasOwnProperty(resourceType)) {
            if (this.gameData.resources[resourceType] >= amount) {
                this.gameData.resources[resourceType] -= amount;
                return true;
            }
        }
        return false;
    }

    /**
     * 检查资源是否足够
     * @param {Object} cost - 成本对象 {wood: 10, food: 20}
     * @returns {boolean} 是否足够
     */
    hasEnoughResources(cost) {
        for (const [resource, amount] of Object.entries(cost)) {
            if (!this.gameData.resources.hasOwnProperty(resource)) {
                return false;
            }
            if (this.gameData.resources[resource] < amount) {
                return false;
            }
        }
        return true;
    }

    /**
     * 扣除多个资源
     * @param {Object} cost - 成本对象 {wood: 10, food: 20}
     * @returns {boolean} 是否成功扣除
     */
    deductResources(cost) {
        // 先检查是否足够
        if (!this.hasEnoughResources(cost)) {
            return false;
        }

        // 扣除资源
        for (const [resource, amount] of Object.entries(cost)) {
            this.gameData.resources[resource] -= amount;
        }

        return true;
    }

    /**
     * 增加人口上限
     * @param {number} amount - 增加的数量
     */
    increaseMaxPopulation(amount) {
        this.gameData.resources.maxPopulation += amount;
    }

    /**
     * 获取资源信息
     * @returns {Object} 资源信息
     */
    getResourcesInfo() {
        return {
            wood: {
                amount: Math.floor(this.gameData.resources.wood),
                production: this.getProductionPerHour('wood')
            },
            food: {
                amount: Math.floor(this.gameData.resources.food),
                production: this.getProductionPerHour('food')
            },
            population: {
                current: this.gameData.resources.population,
                max: this.gameData.resources.maxPopulation
            }
        };
    }
}
